/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.hyk.appcfg.wrapper.util;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Administrator
 */
public class SimpleXmlFileModifier {

    public static void modify(String file, String tagName, String newValue) throws FileNotFoundException, IOException
    {
        FileReader reader = new FileReader(file);
        StringBuffer buffer = new StringBuffer();
        char[] buf = new char[1024];
        int  len = reader.read(buf);
        while(len > 0)
        {
            buffer.append(buf, 0, len);
            len = reader.read(buf);
        }
        reader.close();
        String content = buffer.toString();
        String startTag = "<" + tagName+">";
        String endTag = "</" + tagName+">";
        Pattern p = Pattern.compile(".*("+startTag+".*" + endTag + ").*", Pattern.DOTALL);
        Matcher m = p.matcher(content);
        m.matches();
        String target = m.group(1);
        String newContent = content.replace(target, startTag + newValue + endTag);
        FileWriter writer = new FileWriter(file);
        writer.write(newContent);
        writer.close();
    }

}
